/**
 * Original source:
 * http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=6699aa41-7b59-40ec-a30d-da3afe63bd05
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Weys.Lib
{
    /// <summary>
    /// This structure defines the layout in memory of a 24 bits per pixel rgb format image
    /// </summary>
    public struct PixelData
    {
        /// <summary>
        /// blue value of the pixel
        /// </summary>
        public byte blue;
        /// <summary>
        /// green value of the pixel
        /// </summary>
        public byte green;
        /// <summary>
        /// red value of the pixel
        /// </summary>
        public byte red;
        /// <summary>
        /// alpha value of the pixel
        /// </summary>
        public byte alpha;



        /// <summary>
        /// Judge whether current PixelData is equal to <paramref name="data"/> within the range of <paramref name="thres"/>
        /// </summary>
        /// <param name="data">another PixelData</param>
        /// <param name="thres">the tolerance range</param>
        /// <returns></returns>
        unsafe public bool Equal(PixelData data, int thres)
        {
            int dif = Math.Max(Math.Max(Math.Abs(this.alpha - data.alpha), Math.Abs(this.red - data.red)),
                Math.Max(Math.Abs(this.green - data.green), Math.Abs(this.blue - data.blue)));
            //the maximum difference between two pixeldata in ARGB
            //int dif = Math.Abs(this.alpha - data.alpha) + Math.Abs(this.red - data.red) + Math.Abs(this.green - data.green) + Math.Abs(this.blue - data.blue);

            return (dif <= thres);

        }

        /// <summary>
        /// Judge whether current PixelData is equal to <paramref name="c"/> within the range of <paramref name="thres"/>
        /// </summary>
        /// <param name="c">the color to be compared with</param>
        /// <param name="thres">the tolerace range for color difference</param>
        /// <returns></returns>
        unsafe public bool Equal(Color c, int thres)
        {
            int dif = Math.Max(Math.Max(Math.Abs(this.alpha - c.A), Math.Abs(this.red - c.R)),
                Math.Max(Math.Abs(this.green - c.G), Math.Abs(this.blue - c.B)));
            //the maximum difference between two pixeldata in ARGB
            //int dif = Math.Abs(this.alpha - c.A) + Math.Abs(this.red - c.R) + Math.Abs(this.green - c.G) + Math.Abs(this.blue - c.B);
            return (dif <= thres);

        }

        /// <summary>
        /// convert RGBA to grayscale
        /// </summary>
        /// <returns></returns>
        unsafe public byte ConvertToGrayscale() //chq trace
        {
            return (byte)((byte)(0.299 * this.red + 0.587 * this.green + 0.114 * this.blue));
        }
    }
}

